<template>
  <wd-notice-bar
    text="关注公众号一诺滚雪球获取体验账号"
    prefix="sound"
    type="warning"
    custom-class="space"
  />
  <wd-tabs v-model="tab" swipeable custom-class="mt-4">
    <wd-form ref="form" :model="model" errorType="toast">
      <block v-for="item in tabList" :key="item">
        <wd-tab :title="item.title">
          <wd-cell-group border>
            <wd-input
              v-model="model.value1"
              :label="value1Label"
              label-width="80px"
              prop="value1"
              center
              :placeholder="`请输入${value1Label}`"
              :rules="[{ required: true, message: `请输入${value1Label}` }]"
            >
              <template v-if="tab" #suffix>
                <wd-button
                  size="small"
                  class="text-12px"
                  :disabled="disabled"
                  @click="getCode"
                >
                  {{ codeText }}
                </wd-button>
              </template>
            </wd-input>
            <wd-input
              v-model="model.value2"
              :label="value2Label"
              label-width="80px"
              prop="value2"
              :show-password="!tab"
              :placeholder="`请输入${value2Label}`"
              :rules="[{ required: true, message: `请填写${value2Label}` }]"
            />
          </wd-cell-group>

          <div class="flex px-15px my-4">
            <wd-checkbox v-model="isAgree">阅读并同意</wd-checkbox>
            <div class="text-14px color-blue" @click="openContract">
              {{ privacyContractName }}
            </div>
          </div>
          <view class="footer mt-4 mx-4">
            <wd-button
              type="primary"
              :disabled="
                Boolean(
                  !model.value1 ||
                    !model.value2 ||
                    (tab && model.value2.length !== 6)
                )
              "
              size="large"
              block
              @click="handleSubmit"
            >
              提交
            </wd-button>
          </view>
        </wd-tab>
      </block>
    </wd-form>
  </wd-tabs>
  <!-- #ifndef MP-WEIXIN -->
  <div class="center mt-4">
    <wd-button type="text" @click="goRegister">暂无账号，去注册</wd-button>
  </div>
  <!-- #endif  -->
  <wd-toast />
  <div class="mt-4">
    <official-account />
  </div>
</template>
<script lang="ts">
export default {
  options: {
    // virtualHost: true,
    // addGlobalClass: true,
    styleIsolation: 'shared'
  }
};
</script>
<script setup lang="ts">
import { login, getEmailCode } from '@/api/user';
import { TLoginReq } from '@/api/user/type';
import { ResultCodeEnum } from '@/enums';
import { useUserStore } from '@/store';
import { useToast } from 'wot-design-uni';
import { usePrivacy } from '@/composables/privacy';
console.log('打印***getCur', getCurrentPages());

const redirect_url = ref('/pages/center/index');
onLoad((options) => {
  console.log('打印***options', options);
  if (options && options.redirect_url) {
    redirect_url.value = decodeURIComponent(options.redirect_url);
  }
});

const { isAgree, privacyContractName, openContract } = usePrivacy();
const userStore = useUserStore();
const { success: showSuccess, info } = useToast();

const tab = ref(0);
const tabList = ref([
  {
    title: '账号密码登录',
    type: 'password'
  },
  {
    title: '邮箱登录',
    type: 'email'
  }
]);

const value1Label = computed(() => {
  return tabList.value[tab.value].type === 'password' ? '用户名' : '邮箱';
});

const value2Label = computed(() => {
  return tabList.value[tab.value].type === 'password' ? '密码' : '验证码';
});

const form = ref();
const model = reactive({
  value1: '',
  value2: ''
});

watch(
  () => tab.value,
  () => {
    model.value1 = '';
    model.value2 = '';
  }
);

const codeText = computed(() => {
  if (
    !model.value1 ||
    (!isFetching.value && model.value1) ||
    (!isFetching.value && !time.value)
  )
    return '获取验证码';
  if (isFetching && time) return `${time.value / 1000}s后重新获取`;
});
const time = ref(0);
const isFetching = ref(false);
const disabled = computed(() => {
  console.log(
    '打印***!model.value1 || isFetching.value',
    !model.value1 || isFetching.value
  );
  return !model.value1 || isFetching.value;
});

const getCode = async () => {
  isFetching.value = true;
  time.value = 60 * 1000;
  const id = setInterval(() => {
    time.value -= 1000;
    if (time.value === 0) {
      clearInterval(id);
      isFetching.value = false;
    }
  }, 1000);
  const { code, data } = await getEmailCode(model.value1);
  if (code === ResultCodeEnum.SUCCESS) {
    showSuccess({ msg: data });
  }

  console.log('getCode');
};

const handleSubmit = async () => {
  const { valid } = await form.value.validate();
  if (!valid) return;
  if (!isAgree.value) return info({ msg: '请阅读并同意隐私保护指引' });

  const value1 = model.value1.trim();
  const value2 = model.value2.trim();
  const params: TLoginReq = tab.value
    ? { email: value1, code: value2 }
    : { name: value1, password: value2 };

  const { code, data } = await login(params);
  if (code === ResultCodeEnum.SUCCESS) {
    showSuccess({
      msg: '登录成功'
    });
    userStore.setUserInfo(data);
    setTimeout(() => {
      uni.switchTab({
        url: redirect_url.value,
        fail() {
          uni.navigateTo({ url: redirect_url.value });
        }
      });
    }, 500);
  }
};

const goRegister = () => {
  uni.navigateTo({
    url: '/pages/center/register/index'
  });
};
</script>

<style lang="scss" scoped></style>
